package com.gitee.huanminabc.jlambda_sql.warapper;

import com.gitee.huanminabc.jcommon.reflect.AnnotationUtil;
import com.gitee.huanminabc.jcommon.reflect.FieldUtil;
import com.gitee.huanminabc.jcommon.str.StringUtil;
import com.gitee.huanminabc.jlambda_sql.annotation.TableField;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 简要描述
 *
 * @Author: huanmin
 * @Date: 2025/4/6 11:17
 * @Version: 1.0
 * @Description: 文件作用详细描述....
 */
public class LambdaUpdateWrapper <T>  extends DefaultWhereWrapper<T,LambdaUpdateWrapper<T>>{

    //关联主表, 这个实体用于接收查询结果的,无须和数据库表完全对应
    public static <T> LambdaUpdateWrapper<T> create(T entity){
        return new LambdaUpdateWrapper<>(entity);
    }
    public static <T> LambdaUpdateWrapper<T> create(Class<T> tClass){
        return new LambdaUpdateWrapper<>(tClass);
    }
    private LambdaUpdateWrapper(Class<T> tClass) {
        super(LambdaWrapper.create(tClass));
        typedThis.UPDATE().TABLE();
    }

    //默认别名 t1
    private LambdaUpdateWrapper(T entity) {
        super((LambdaWrapper<T>) LambdaWrapper.create(entity.getClass()));
        typedThis.UPDATE().TABLE().SET();
        Map<Field, TableField> annotationsFieldMap = AnnotationUtil.getAnnotationsFieldMap(entity.getClass(), TableField.class);
        for (Map.Entry<Field, TableField> fieldTableFieldEntry : annotationsFieldMap.entrySet()) {
            Field field = fieldTableFieldEntry.getKey();
            TableField tableField = fieldTableFieldEntry.getValue();
            String fieldName = tableField.value();
            if (StringUtil.isEmpty(fieldName)) {
                fieldName = field.getName();
            }
            fieldName = typedThis.getTableInfo().getAlias() + "." + fieldName;
            Object fieldValue = FieldUtil.getFieldValue(field, entity);
            if (fieldValue == null) {
                continue;
            }
            typedThis.FIELD(fieldName).EQ(fieldValue).COMMA();
        }
        typedThis.WHERE();
    }

}
